﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace BP.OA.UI
{
    public class FileUpload
    {
        /// <summary>
        /// 总目录变量接口
        /// </summary>
        private string __GeneUploadDir = "/UploadFiles/";
        /// <summary>
        /// 上传控件FileUpload
        /// </summary>
        private System.Web.UI.WebControls.FileUpload __FileUpload_Ctrl = null;
        /// <summary>
        /// 上传文件组名，它可以最终找到目录
        /// </summary>
        private String __FileGroup_Name = null;
        /// <summary>
        /// 定义函数
        /// </summary>
        /// <param name="fileGroup">文件组名，为获取文件目录</param>
        /// <param name="fu">上传组件</param>
        public FileUpload(String fileGroup, System.Web.UI.WebControls.FileUpload fu)
        {
            this.__FileGroup_Name = fileGroup;
            this.__FileUpload_Ctrl = fu;
        }
        /// <summary>
        /// 获取路径函数，根据文件组名获取文件目录。
        /// </summary>
        /// <returns></returns>
        protected virtual string GetAttachPathName()
        {
            string dir = String.Format("{2}{1}/{0:yyyyMMdd}", DateTime.Now, this.__FileGroup_Name, this.__GeneUploadDir);
            return dir;
        }
        /// <summary>
        /// 获取新文件名函数，根据原文件名，得到新文件名
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        protected virtual string GetAttachFileName(string fileName)
        {
            string f = System.IO.Path.GetFileNameWithoutExtension(fileName);
            string ext = System.IO.Path.GetExtension(fileName);
            string newFileName = String.Format("{0}_{1:yyyyMMddHHmmss}{2}", f, DateTime.Now, ext);
            return newFileName;
        }
        /// <summary>
        /// 根据存储路径获取老文件名，必须是存储路径中包含老文件名才可。
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public virtual string GetAttachOldFileName(string savePath)
        {
            String attachFile = System.IO.Path.GetFileName(savePath);
            String ext = System.IO.Path.GetExtension(savePath);

            //String[] arr_attachFile = attachFile.Split('_');
            //return String.Format("{0}{1}", arr_attachFile[0], ext);

            int index = attachFile.LastIndexOf('_');
            string oldName = attachFile.Substring(0, index);
            //String[] arr_attachFile = attachFile.Split('_');
            return String.Format("{0}{1}", oldName, ext);
        }
        /// <summary>
        /// 多文件上传，这个上传必须是用到FileUploadCtrl用不到，可以为为空。
        /// </summary>
        /// <param name="oldPaths">网站地址列表，如果有必须与HttpPostedFile相对应，不是磁盘地址</param>
        public string[] SaveAllRequest(params string[] oldPaths)
        {
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(dir));

            List<String> ls_newPath = new List<string>();
            for (int i=0;i<HttpContext.Current.Request.Files.Count;i++)
            {
                HttpPostedFile hpf = HttpContext.Current.Request.Files[i];
                string oldPath = null;
                if (i <= oldPaths.Length - 1) oldPath = oldPaths[i];

                String newPath = oldPath;

                if (hpf.ContentLength > 0)
                {                    
                    string newFileName = this.GetAttachFileName(hpf.FileName);

                    string path = String.Format("{0}/{1}", dir, newFileName);

                    try
                    {
                        hpf.SaveAs(HttpContext.Current.Server.MapPath(path));
                        newPath = path;
                        if (!String.IsNullOrEmpty(oldPath))
                        {
                            System.IO.File.Delete(HttpContext.Current.Server.MapPath(oldPath));
                        }
                    }
                    catch
                    {
                        ;
                    }
                }
                ls_newPath.Add(newPath);
            }
            return ls_newPath.ToArray();
        }
        /// <summary>
        /// 单个上传，这个上传必须是用到FileUploadCtrl不能为空。
        /// </summary>
        /// <param name="oldPath">网站地址，不是磁盘地址</param>
        public string Save(string oldPath)
        {
            string newPath = oldPath;
            if (this.__FileUpload_Ctrl.HasFile)
            {
                string dir = this.GetAttachPathName();
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(dir)))
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(dir));

                string newFileName = this.GetAttachFileName(this.__FileUpload_Ctrl.FileName);

                string path = String.Format("{0}/{1}", dir, newFileName);

                try
                {
                    this.__FileUpload_Ctrl.SaveAs(HttpContext.Current.Server.MapPath(path));
                    newPath = path;
                    if (!String.IsNullOrEmpty(oldPath))
                    {
                        System.IO.File.Delete(HttpContext.Current.Server.MapPath(oldPath));
                    }
                }
                catch
                {
                    ;
                }

            } 
            return newPath;
        }
    }
}
